package com.spzx.manager.config;

import com.spzx.manager.intercetor.LoginAuthInterceptor;
import com.spzx.manager.properties.UserAuthProperties;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * 跨域处理
 * Project: spzx-parent
 * Package: com.spzx.manager.config
 * Version: 1.0
 * <p>
 * Created by  wangjiaxin  on 2023/11/30 23:29
 */
@Component
public class WebMvcConfiguration implements WebMvcConfigurer {

    @Resource
    private LoginAuthInterceptor loginAuthInterceptor;

    @Resource
    private UserAuthProperties userAuthProperties;

    /**
     * 配置类配置跨域请求
     *
     * @param registry
     */
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")      // 添加路径规则
                .allowCredentials(true)               // 是否允许在跨域的情况下传递Cookie
                .allowedOriginPatterns("*")           // **允许请求来源的域规则**
                .allowedMethods("*")
                .allowedHeaders("*");                // 允许所有的请求头
    }

    /**
     * 拦截器注册
     *
     * @param registry
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(loginAuthInterceptor)
                .excludePathPatterns(userAuthProperties.getNoAuthUrls())  //放行的接口
                .addPathPatterns("/**");      //需要拦截的接口
    }
}
